#include "app_message.h"
#include "app_common.h"
#include "log.h"
#include "string.h"
#include "unistd.h"
#include "cJSON.h"
#include "stdlib.h"

Message *app_message_bytes_to_message(char *bytes, int bytes_len)
{
    // 1.先创建一个Message
    Message *message = (Message *)malloc(sizeof(Message));
    if (message == NULL)
    {
        perror("message malloc failed...");
        return NULL;
    }

    // 2.提取数据
    message->conn_type = bytes[0];
    message->id_len = bytes[1];
    message->msg_len = bytes[2];
    message->payload = (char *)malloc(bytes_len - 3);
    memcpy(message->payload, bytes + 3, bytes_len - 3);

    return message;
}

int app_message_to_message_bytes(Message *message, char *bytes_buff, int buff_len)
{
    int bytes_len = message->id_len + message->msg_len + 3;
    bytes_buff[0] = message->conn_type;
    bytes_buff[1] = message->id_len;
    bytes_buff[2] = message->msg_len;

    memcpy(bytes_buff + 3, message->payload, message->id_len + message->msg_len);
    return bytes_len;
}

char *app_message_to_message_json(Message *message)
{
    cJSON *json = cJSON_CreateObject();

    // 连接类型
    cJSON_AddNumberToObject(json, "conn_type", message->conn_type);
    char *id_bytes = malloc(message->id_len);
    char *msg_bytes = malloc(message->msg_len);

    memcpy(id_bytes, message->payload, message->id_len);
    memcpy(msg_bytes, message->payload + message->id_len, message->msg_len);

    // 把字节数组转换为16进制的字符串
    char *id_json_str = app_common_bytes2hexstr(id_bytes, message->id_len);
    char *msg_json_str = app_common_bytes2hexstr(msg_bytes, message->msg_len);

    // 填入json对象
    cJSON_AddStringToObject(json, "id", id_json_str);
    cJSON_AddStringToObject(json, "msg", msg_json_str);

    // 打印json字符串
    char *json_str = cJSON_PrintUnformatted(json);

    // 释放空间
    free(id_bytes);
    free(msg_bytes);
    cJSON_Delete(json);

    return json_str;
}

Message *app_message_json_to_message(char *json)
{
    cJSON *json_obj = cJSON_Parse(json);
    if (json_obj == NULL)
    {
        log_error("cJSON Parse failed...");
    }

    cJSON *conn_type_json = cJSON_GetObjectItem(json_obj, "conn_type");
    cJSON *id_json = cJSON_GetObjectItem(json_obj, "id");
    cJSON *msg_json = cJSON_GetObjectItem(json_obj, "msg");

    // 构造Message结构体
    Message *message = (Message *)malloc(sizeof(Message));
    message->conn_type = conn_type_json->valueint;
    message->id_len = strlen(id_json->valuestring) / 2;
    message->msg_len = strlen(msg_json->valuestring) / 2;

    // 把16进制的字符串转换为字节数组
    char id_bytes[message->id_len];
    char msg_bytes[message->msg_len];
    int id_len = app_common_hexstr2bytes(id_json->valuestring, id_bytes);
    int msg_len = app_common_hexstr2bytes(msg_json->valuestring, msg_bytes);
    // 放入结构体的变量
    message->payload = (char *)malloc(id_len + msg_len);
    memcpy(message->payload, id_bytes, id_len);
    memcpy(message->payload + id_len, msg_bytes, msg_len);

    return message;
}
